package dao

import (
	"disk/service/user/dao/service"
	"disk/utils/mysql"
	"gorm.io/gorm"
	"log"
)

func GetUserByName(name string) []mysql.UserList {
	var userList []mysql.UserList
	userList = service.GetFromRedisByName(name)
	// 如果redis中没有缓存，则查询MySQL数据库
	if userList != nil {
		return userList
	} else {
		lock := service.GetRedLock(name)
		if err := lock.Lock(); err != nil {
			log.Println("获取锁失败:", err)
			return nil
		}
		defer lock.Unlock()
		go service.ContinueLock(lock)

		db := service.Database.Session(&gorm.Session{NewDB: true})
		err := db.Where("name = ?", name).Find(&userList).Error
		if err != nil {
			return nil
		}
		service.SetNameToRedis(name, userList)
	}

	return userList
}
